/**
 * @a https://leetcode.cn/problems/contiguous-array/
 */

#include "common.h"

class Solution
{
public:
    int findMaxLength(vector<int> &nums)
    {
        unordered_map<int, int> hash;
        int sum = 0, ret = 0;
        /*返回多少个1和0个数相同的代码*/
        // for (auto num : nums)
        // {
        //     sum += (num == 0) ? -1 : 1;
        //     if(hash.count(-sum)) ret+=hash[-sum];
        //     ++hash[-sum];
        // }
        // return ret;
        
        /*题目要求的代码*/
        hash[0] = -1;
        size_t sz = nums.size();
        for(int i = 0; i < sz; ++i)
        {
            sum += (nums[i] == 0) ? -1 : 1;
            if(hash.count(sum)) ret = max(ret, i - hash[sum]);
            else hash[sum] = i;
        }
        return ret;
    }
};